<!-- 入库收货单 -->
<template>
  <div>
    <ChooseShow :menus="WarehousesTree.ReturnData||[]" @GetTableId="GetTableId">
      <div class="process" slot="operation">
        <div>
          <el-button type="primary" @click="addEvent">新增</el-button>
        </div>
        <div class="filter">
          <el-checkbox-group
            v-model="checkData"
            @change="handleConditionChange"
            class="checkMargin"
          >
            <el-checkbox
              v-for="(item, index) in checkList"
              :key="index"
              :label="item.statu"
            >{{item.title}}</el-checkbox>
          </el-checkbox-group>
          <div class="search">
            <el-input
              placeholder="请输入内容"
              prefix-icon="el-icon-search"
              v-model="searchKey"
              @change="handleInputChange"
            ></el-input>
            <el-button icon="el-icon-refresh" size="small" class="refresh" @click="refreshPage"></el-button>
          </div>
        </div>
      </div>
      <div slot="table">
        <el-table :data="tabledata">
          <template v-for="(item,index) in columns">
            <el-table-column
              v-if="item.title=='操作'"
              :key="index"
              :label="item.title"
              :prop="item.key"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.Status=='挂单'"
                  type="text"
                  size="small"
                  @click="check(scope.row,true)"
                >编辑</el-button>
                <el-button
                  v-if="scope.row.Status=='挂单'"
                  type="text"
                  size="small"
                  @click="deletes(scope.row)"
                >删除</el-button>
                <el-button v-else type="text" size="small" @click="check(scope.row,true)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column
              v-else
              :key="index"
              :label="item.title"
              :prop="item.key"
              align="center"
            ></el-table-column>
          </template>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total"
          align="right"
          class="pagination"
        ></el-pagination>
      </div>
    </ChooseShow>

    <el-dialog
      class="ModalForm"
      width="50%"
      @close="PopFormInit"
      :visible.sync="modal12"
      :closeOnClickModal="false"
      scrollabel
      :title="disabled?'查看入库单':'新增入库单'"
    >
      <PopForm
        ref="PopForm"
        @addbtn="addbtn"
        :fromData="fromData"
        :disabled="disabled"
        class="PopForm"
      >
        <div slot="tabPane0">
          <el-table size="small" :data="tabledata01" :header-cell-style="{background: '#DCDFE6'}">
            <template v-for="(item,index) in fromData.tabPane[0].columns">
              <el-table-column
                v-if="item.title=='操作'"
                :label="item.title"
                :prop="item.key"
                align="center"
                fixed="right"
                width="100"
                :key="index"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="disabled"
                    type="text"
                    size="small"
                    @click="EditMateriels(scope.row,false)"
                  >查看</el-button>
                  <template v-else>
                    <el-button type="text" size="small" @click="EditMateriels(scope.row,true)">编辑</el-button>
                    <el-button type="text" size="small" @click="RemoveMateriels(scope.row)">删除</el-button>
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                v-else
                :show-overflow-tooltip="true"
                :label="item.title"
                :prop="item.key"
                align="center"
                :key="index"
              ></el-table-column>
            </template>
          </el-table>
        </div>
      </PopForm>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="disabled" style="font-size:12px" type="primary">挂 单</el-button>
        <el-button :disabled="disabled" style="font-size:12px" type="primary" @click="Commit">提 交</el-button>
        <el-button style="font-size:12px" @click="PopFormInit">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      class="ModalForm"
      width="460px"
      @close="PopFormInit01"
      :visible.sync="modal13"
      :closeOnClickModal="false"
      scrollabel
      :title="disabled?'入库物料查看':'入库物料新增'"
    >
      <PopForm ref="PopForm01" :fromData="fromData01" :disabled="disabled" :flex="false">
        <el-select
          slot="selectremote"
          v-model="remotevalue"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="remoteloading"
        >
          <el-option v-for="item in options" :key="item.Id" :label="item.Name" :value="item.Id"></el-option>
        </el-select>
      </PopForm>
      <div class="dialog-footer">
        <el-button
          :disabled="disabled"
          style="font-size:12px"
          type="primary"
          @click="AddMateriels"
        >确 定</el-button>
        <el-button style="font-size:12px" @click="PopFormInit01">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import PopForm from "@/components/PopForm";
import ChooseShow from "@/components/ChooseShow";
import fromdata from "@/const/index";
import show01 from "@/const/chooseshow";
export default {
  name: "",
  data() {
    return {
      disabled: false,
      remotevalue: "",
      options: [],
      remoteloading: false,
      drawerloading: true,
      direction: false,
      checkData: [],
      searchKey: "",
      Id: "1",
      units: {},
      unitsId: 1,
      Type: [
        "采购单",
        "调拨入库",
        "盘点入库",
        "退仓入库",
        "工具归还",
        "其他入库"
      ],
      modal12: false,
      modal13: false,
      fromData: {},
      currentPage: 1,
      pageSize: 10,
      total: 50,
      tabledata: [],
      tabledata01: [],
      columns: [],
      Status: ["", "", "正式", "挂单"],
      checkList: [
        {
          title: "全部下级",
          statu: 2
        },
        {
          title: "已停用",
          statu: 3
        }
      ]
    };
  },
  computed: {
    ...mapGetters([
      "WarehousesTree",
      "InStocks",
      "InStockById",
      "Materiels",
      "MaterielById",
      "UnitConvertsByMaterielId",
      "UnitConvertById",
      "removeInStock",
      "saveInStock"
    ])
  },
  components: {
    PopForm,
    ChooseShow
  },
  watch: {
    WarehousesTree: function(newval, oldval) {
      this.GetInStocks();
    },
    InStocks: function(newval, oldval) {
      this.total = newval.ReturnData.DataCount;
      if (
        newval.ReturnData &&
        newval.ReturnData.Data &&
        newval.ReturnData.Data.length > 0
      ) {
        newval.ReturnData.Data.forEach(element => {
          for (const key in element) {
            if (key == "SourceTable") {
              element.Type = this.Type[element.Type];
            }
            if (key == "Status") {
              element.Status = this.Status[element.Status];
            }
          }
        });
        this.tabledata = newval.ReturnData.Data;
      } else {
        this.tabledata = [];
      }
    },
    Materiels: function(newval, oldval) {
      this.remoteloading = false;
      this.options = newval.ReturnData.Data;
    },
    UnitConvertsByMaterielId: function(newval, oldval) {
      if (newval && newval.ReturnData && newval.ReturnData.length > 0) {
        newval.ReturnData.forEach(element => {
          element.value = element.Id;
          element.label = element.Name;
        });
      }
      this.$refs.PopForm01.Changeoptions(newval.ReturnData, 3);
    },
    UnitConvertById: function(newval, oldval) {
      let obj = newval.ReturnData;
      let arr = [];
      obj.value = obj.Id;
      obj.label = obj.Name;
      arr.push(obj);
      this.$refs.PopForm01.Changeoptions(arr, 3);
    },
    remotevalue: function(newval, oldval) {
      if (newval !== "") {
        this.GetUnitConvertsByMaterielId(newval);
      }
    },
    removeInStock: function(newval, oldval) {
      if (newval.Code == 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        this.GetInStocks();
      } else {
        this.$message({
          type: "error",
          message: "删除失败"
        });
      }
    },
    saveInStock: function(newval, oldval) {
      if (newval.Code == 0) {
        this.$message({
          type: "success",
          message: "提交成功"
        });
        this.GetInStocks();
      } else {
        this.$message({
          type: "error",
          message: "提交失败"
        });
      }
    },
    InStockById: function(newval, oldval) {
      this.tabledata01 = newval.ReturnData.InStockDetail || [];
      this.tabledata01.forEach(element => {
        element.No = element.MaterielNo;
        element.Name = element.MaterielName;
        element.Spec = element.MaterielSpec;
        element.Model = element.MaterielModel;
      });
    }
  },
  methods: {
    // 物料删除
    RemoveMateriels(val) {
      for (let index = 0; index < this.tabledata01.length; index++) {
        const element = this.tabledata01[index];
        if (element.MaterielId == val.MaterielId) {
          this.tabledata01.splice(index, 1);
        }
      }
    },
    // 物料编辑
    EditMateriels(val, istrue) {
      this.modal13 = true;
      setTimeout(() => {
        let PopFormdata = JSON.parse(
          JSON.stringify(this.$refs.PopForm01.value)
        );
        for (const key in PopFormdata) {
          this.remotevalue = val.MaterielId;
          if (key == "MaterielId") {
            if (istrue) {
              this.GetUnitConvertById(val.UnitId);
            }
          } else {
            PopFormdata[key] = val[key] || "";
          }
        }
        this.$refs.PopForm01.value = PopFormdata;
      });
    },
    // select远程搜索回调
    remoteMethod(query) {
      if (query !== "") {
        this.remoteloading = true;
        this.GetMateriels(query);
      } else {
        this.options = [];
      }
    },
    // ==========表格===============
    // 上一页
    handlePrevClick(val) {
      this.currentPage = val;
      if (val < 1) {
        this.currentPage = 1;
      }

      this.GetInStocks();
    },
    // 下一页
    handleNextClick(val) {
      this.currentPage = val;
      if (val > this.total) {
        this.currentPage = this.total;
      }
      this.GetInStocks();
    },
    // 当前页改变时会触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.GetInStocks();
    },
    // pageSize 改变时会触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.GetInStocks();
    },
    // 筛选框value发生改变的回调
    handleInputChange(val) {
      this.searchKey = val;
      this.GetInStocks();
    },
    // 新增入库单
    addEvent() {
      this.disabled = false;
      this.modal12 = true;
    },
    // 多选框回调
    handleConditionChange(val) {
      this.checkData = val;
      this.GetInStocks();
    },
    // 刷新
    refreshPage() {
      this.GetInStocks();
    },
    // 新增入库物料
    addbtn(e) {
      this.modal13 = true;
      // this.GetMateriels();
    },
    // 表格删除事件的回调
    deletes(val) {
      this.$confirm("此操作将永久删除" + val.No + ",是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.RemoveInStock(val);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 表格查看事件的回调
    check(val, disabled = false) {
      this.modal12 = true;
      setTimeout(() => {
        let value = this.$refs.PopForm.value;
        this.disabled = disabled;
        let obj = {};
        for (
          let index = 0;
          index < this.fromData.fromComponent.length;
          index++
        ) {
          const element = this.fromData.fromComponent[index].key;
          obj[element] = val[element] || "";
        }
        obj.Id = val.Id;
        this.$refs.PopForm.value = obj;
      });
      this.GetInStockById(val.Id);
    },
    // 左侧导航栏事件的回调
    GetTableId(val) {
      this.Id = val.Id;
      this.GetInStocks();
    },
    // 弹出框表单提交
    Commit() {
      this.$refs.PopForm.$refs.ruleForm.validate(valid => {
        if (valid) {
          let value = JSON.parse(JSON.stringify(this.$refs.PopForm.value));
          value.InStockDetail = this.tabledata01;
          value.TableType = 1;
          this.SaveInStock(value);
          this.PopFormInit();
        } else {
          return false;
        }
      });
    },
    // 弹出框表单初始化
    PopFormInit() {
      this.tabledata01 = [];
      this.$refs.PopForm.$refs.ruleForm.resetFields();
      this.modal12 = false;
    },
    PopFormInit01() {
      this.remotevalue = "";
      this.$refs.PopForm01.$refs.ruleForm.resetFields();
      this.modal13 = false;
    },
    // 新增物料提交
    AddMateriels() {
      let exist = false;
      let isnum = 0;
      if (this.tabledata01.length > 0) {
        this.tabledata01.forEach((element, index) => {
          if (element.MaterielId == this.remotevalue) {
            exist = true;
            isnum = index;
          }
        });
      }
      let element;
      if (exist) {
        element = JSON.parse(JSON.stringify(this.tabledata01[isnum]));
        for (const key in this.$refs.PopForm01.value) {
          element[key] = this.$refs.PopForm01.value[key];
        }
      } else {
        element = this.$refs.PopForm01.value;
      }
      let obj = {
        MaterielId: element.MaterielId || this.remotevalue || "",
        No: element.No || "",
        Name: element.Name || "",
        Spec: element.Spec || "",
        Model: element.Model || "",
        Batch: element.Batch || "",
        Number: element.Number || "",
        UnitId: element.UnitId || "",
        Price: element.Price || "",
        Amount: element.Amount || 0,
        Remark: element.Remark || ""
      };
      if (exist) {
        this.tabledata01.splice(isnum, 1, obj);
        this.$message.success("物料 " + obj.Name + " 已修改");
      } else {
        for (let index = 0; index < this.options.length; index++) {
          const element = this.options[index];
          if (element.Id == this.remotevalue) {
            obj.No = element.No;
            obj.Name = element.Name;
            obj.Spec = element.Spec;
            obj.Model = element.Model;
          }
        }
        this.tabledata01.push(obj);
      }
      this.PopFormInit01();
    },
    // 弹出框底部标签页组件事件的回调
    edit(val) {
      console.log(val);
    },
    // 获取仓库树
    GetWarehousesTree() {
      let json = {
        MN: "GetWarehousesTree",
        DataContent: {}
      };
      this.MIX_send(json);
    },
    // 获取仓储表格数据
    GetInStocks() {
      let json = {
        MN: "GetInStocks",
        DataContent: {
          WarehouseId: this.Id,
          KeyWord: this.searchKey,
          PageSize: this.pageSize,
          PageIndex: this.currentPage,
          Status: this.checkData.join(",")
        }
      };
      this.MIX_send(json);
    },
    // 获取所有物料
    GetMateriels(val) {
      let json = {
        MN: "GetMateriels",
        DataContent: {
          CategoryId: 0,
          Status: "",
          KeyWord: val,
          PageSize: 10,
          PageIndex: 1
        }
      };
      this.MIX_send(json);
    },
    // 根据物料id获取单位
    GetUnitConvertsByMaterielId(val) {
      let json = {
        MN: "GetUnitConvertsByMaterielId",
        DataContent: {
          MaterielId: val
        }
      };
      this.unitsId = val;
      if (!this.units[val]) {
        this.MIX_send(json);
      }
    },
    // 根据id获取单位
    GetUnitConvertById(val) {
      let json = {
        MN: "GetUnitConvertById",
        DataContent: {
          Id: val
        }
      };
      this.MIX_send(json);
    },
    // 删除入库单
    RemoveInStock(val) {
      let json = {
        MN: "RemoveInStock",
        DataContent: {
          Ids: val.Id
        }
      };
      this.MIX_send(json);
    },
    // 保存/提交入库单
    SaveInStock(obj) {
      let json = {
        MN: "SaveInStock",
        DataContent: obj
      };
      this.MIX_send(json);
    },
    // 获取入库单明细
    GetInStockById(id) {
      let json = {
        MN: "GetInStockById",
        DataContent: {
          Id: id
        }
      };
      this.MIX_send(json);
    },
    // 根据Id获取物料信息
    GetMaterielById(id) {
      let json = {
        MN: "GetMaterielById",
        DataContent: {
          Id: id
        }
      };
      this.MIX_send(json);
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.fromData = fromdata.fromdata;
    this.fromData01 = fromdata.fromdata01;
    this.columns = show01().columns;
    this.GetWarehousesTree();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {}
};
</script>
<style scoped>
/* @import url(); 引入css类 */
.dialog-footer {
  margin-top: 15px;
  text-align: right;
}
.process {
  height: 56px;
  line-height: 56px;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
.checkMargin {
  margin-right: 20px;
}
.filter {
  display: flex;
}
.search {
  display: flex;
  flex-direction: row;
}
.refresh {
  height: 40px;
  padding: 0;
  width: 40px;
  margin-top: 8px;
  margin-left: 10px;
}
.pagination {
  margin-top: 40px;
  padding-right: 20px;
}
.PopForm {
  height: 51vh;
  overflow-y: auto;
}
.PopForm::-webkit-scrollbar {
  width: 4px;
}
.PopForm::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(0, 0, 0, 0.2);
}
.PopForm::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}
</style>